import React from 'react';
import PropTypes from 'prop-types';
import { Checkbox, Button } from '@teamix/ui';
import utils from 'utils';
import intl from '../../locale';

export default class SelectMenu extends React.Component {
  static propTypes = {
    data: PropTypes.arrayOf(PropTypes.object),
    onChange: PropTypes.func,
  };

  static defaultProps = {
    data: [],
    onChange: () => {},
    popupClassName: '',
    customizedItemRender: null,
  };

  constructor(props) {
    super(props);
    const { fromIndex, toIndex } = this.getIndex();
    this.state = {
      fromIndex,
      toIndex,
    };
  }

  getIndex = () => {
    const { data, from_commit, to_commit } = this.props;

    if (!data) {
      return {
        toIndex: -1,
        fromIndex: -1,
      };
    }
    const fromIndex = data.findIndex((item) => {
      return from_commit === item.value;
    });
    const toIndex = data.findIndex((item) => {
      return to_commit === item.value;
    });

    // 如果from_commit,to_commit只有一个有值，则去有值的索引
    return {
      toIndex: toIndex === -1 && fromIndex !== -1 ? fromIndex : toIndex,
      fromIndex: toIndex !== -1 && fromIndex === -1 ? toIndex : fromIndex,
    };
  };

  setIndex = (index) => {
    const { fromIndex, toIndex } = this.state;
    // 未点击,fromIndex和toIndex都设置为index.
    // index === fromIndex 或者toIndex: fromIndex ！== toIndex 点击的是边界值，该边界值改变。若相等，则取消
    // 点击后,index < fromIndex时，设置fromIndex，否则只改变toIndex
    if (fromIndex === -1 && toIndex === -1) {
      this.setState({
        fromIndex: index,
        toIndex: index,
      });
    } else if (fromIndex === toIndex && index === fromIndex) {
      this.setState({
        fromIndex: -1,
        toIndex: -1,
      });
    } else if (fromIndex !== toIndex && (index === fromIndex || toIndex === index)) {
      this.setState({
        fromIndex: index === fromIndex ? fromIndex + 1 : fromIndex,
        toIndex: index === toIndex ? toIndex - 1 : toIndex,
      });
    } else if (index < fromIndex) {
      this.setState({
        fromIndex: index,
      });
    } else {
      this.setState({
        toIndex: index,
      });
    }
  };

  handleClose = () => {
    this.props.onClose();
  };

  handleOk = () => {
    const { fromIndex, toIndex } = this.state;
    this.props.onChange({
      fromIndex,
      toIndex,
    });
  };

  renderCommitLabel = (item, index) => {
    const { fromIndex, toIndex } = this.state;
    const { data } = item;
    const authorName = data.author ? data.author.name : data.author_name || '';
    const time = utils.getBeautyTime(data.created_at || data.authored_date).toLowerCase();
    const des = intl.get(
      {
        id: 'code-assets.components.commitSelect.overlay.AuthornameSubmittedAtTime',
        defaultMessage: '{authorName} 提交于 {time}',
      },
      { authorName, time },
    );
    return (
      <div
        className={`commit-select-label ${index >= fromIndex && index <= toIndex ? 'active' : ''}`}
      >
        <div className="selected-icon-wrapper" />
        <div className="commit-select-label-left">
          <div className="commit-select-label-title one-line-ellipsis">{data.title}</div>
          <div className="commit-select-label-des one-line-ellipsis">{des}</div>
        </div>
        <div className="commit-select-label-right">{data.id.slice(0, 8)}</div>
      </div>
    );
  };

  render() {
    const { data } = this.props;
    const { fromIndex, toIndex } = this.state;
    let selectLength = 0;
    if (fromIndex === -1 && toIndex === -1) {
      selectLength = 0;
    } else {
      selectLength = Math.abs(fromIndex - toIndex) + 1;
    }

    if (!data && data.length) {
      return null;
    }

    return (
      <div className={'customized-select-pop-container commit-select-popup overlay-shadow'}>
        <div className="commit-select-popup-header">
          <div>
            <Checkbox
              checked={data.length === selectLength}
              indeterminate={selectLength && data.length > selectLength}
              onChange={(value) => {
                if (value) {
                  this.setState({
                    fromIndex: 0,
                    toIndex: data.length - 1,
                  });
                } else {
                  this.setState({
                    fromIndex: -1,
                    toIndex: -1,
                  });
                }
              }}
            >
              {intl.get({
                id: 'code-assets.components.commitSelect.overlay.SubmitAll',
                defaultMessage: '全部提交',
              })}
            </Checkbox>
          </div>
          <div className="commit-select-popup-header-right">
            {intl.get({
              id: 'code-assets.components.commitSelect.overlay.SelectASingleSubmissionOr',
              defaultMessage: '选择单项提交或提交区间',
            })}
          </div>
        </div>
        <div className="commit-select-popup-body">
          {!!data &&
            data.map((item, index) => {
              return (
                <div
                  onClick={() => {
                    this.setIndex(index);
                  }}
                >
                  {this.renderCommitLabel(item, index)}
                </div>
              );
            })}
        </div>

        <div className="commit-select-popup-footer">
          <div className="commit-select-popup-footer-left">
            {selectLength
              ? intl.get(
                  {
                    id: 'code-assets.components.commitSelect.overlay.SelectlengthSubmitted',
                    defaultMessage: '已选择 {selectLength} 个提交',
                  },
                  { selectLength },
                )
              : ''}
          </div>
          <div className="commit-select-popup-footer-right">
            <Button type="normal" onClick={this.handleClose}>
              {intl.get({
                id: 'code-assets.components.commitSelect.overlay.Cancel',
                defaultMessage: '取消',
              })}
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: 12 }}
              disabled={!selectLength}
              onClick={this.handleOk}
            >
              {intl.get({
                id: 'code-assets.components.commitSelect.overlay.Determine',
                defaultMessage: '确定',
              })}
            </Button>
          </div>
        </div>
      </div>
    );
  }
}
